﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infratructure.Interfares;
using B.S.BaseData.Write.Api.Application.Command.RoleCommand;
using MediatR;

namespace B.S.BaseData.Write.Api.Application.CommandHander.RoleHander
{
    public class AddRoleCommandHander : IRequestHandler<AddRoleCommand, ApiResult<int>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRequsitory<Role> baseRequsitory;

        public AddRoleCommandHander(IMapper mapper, IBaseRequsitory<Role> baseRequsitory)
        {
            this.mapper = mapper;
            this.baseRequsitory = baseRequsitory;
        }
        /// <summary>
        /// 添加角色处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();            
            var entity = mapper.Map<Role>(request);
            entity.UpdateTime = "";
            var one = baseRequsitory.GetAllAsync().Where(x => x.RoleName == request.RoleName).FirstOrDefault();

            if (one!=null)
            {
                result.Code = ApiEnum.用户名不存在;
                result.Msg = ApiEnum.用户名不存在.ToString();
                result.Data = 0;
                return await Task.FromResult(result);
            }

            var list = await baseRequsitory.AddAsync(entity);

            if (list > 0)
            {
                result.Code = ApiEnum.添加成功;
                result.Msg = ApiEnum.添加成功.ToString();
                result.Data = list;
            }
            else
            {
                result.Code = ApiEnum.添加失败;
                result.Msg = ApiEnum.添加失败.ToString();
                result.Data = list;
            }

            return await Task.FromResult(result);
        }
    }
}
